package com.jn.gsondemo;

import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class OlympicMedalActivity extends AppCompatActivity {
    private ListView medalListView;
    private ArrayList<String> medalList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_olympic_medal);

        medalListView = findViewById(R.id.medal_list);
        medalList = new ArrayList<>();

        loadMedalData();
    }

    private void loadMedalData() {
        try {
            InputStream inputStream = getResources().openRawResource(R.raw.olympic);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder stringBuilder = new StringBuilder();
            String line;

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }

            reader.close();
            String json = stringBuilder.toString();
            JSONArray jsonArray = new JSONArray(json);

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                String medalCount = obj.getString("gold") + "金 " + obj.getString("silver") + "银 " + obj.getString("bronze") + "铜";
                medalList.add(obj.getString("country") + " - " + medalCount);
            }

            ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, medalList);
            medalListView.setAdapter(adapter);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}